//
//  NSString+ZZUtil.m
//  OCFrame
//
//  Created by hfzhangzhang on 2016/12/19.
//  Copyright © 2016年 hfzhangzhang. All rights reserved.
//

#import "NSString+ZZUtil.h"

#import <CommonCrypto/CommonDigest.h> // MD5

@implementation NSString (ZZUtil)

- (BOOL)zz_isValidateMobileTel
{
    NSString* mob = @"^1[0-9]{10}$";
    NSPredicate* regexMob = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", mob];
    return [regexMob evaluateWithObject:self];
}

- (BOOL)zz_isValidateEmail{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:self];
}

//身份证号
- (BOOL)zz_isValidateIdentityCard
{
    NSString *regex = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    return [predicate evaluateWithObject:self];
}

/** number */
- (BOOL)zz_isNumber {
    return [self.class evaluateNumberString:self];
}

+ (BOOL)evaluateNumberString:(NSString *)string {
    if ([self zz_evaluateEmptyString:string]) return NO;
    NSCharacterSet *characterSet = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789"] invertedSet];
    NSString *flitered = [[string componentsSeparatedByCharactersInSet:characterSet] componentsJoinedByString:@""];
    return [string isEqualToString:flitered];
}

/** empty */
- (BOOL)zz_isNonEmpty {
    return ![self.class zz_evaluateEmptyString:self];
}

+ (BOOL)zz_evaluateEmptyString:(NSString *)string {
    return string == nil || ![string isKindOfClass:[NSString class]] || [string isEqualToString:@""] || [[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] == 0;
}


+ (instancetype)zz_stringWithJson:(id)json {
    return [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:json options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding];
}

- (id)zz_jsonData {
    return [NSJSONSerialization JSONObjectWithData:[self dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableLeaves error:nil];
}

- (NSString *)zz_trimmedString {
    return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
}

@end


@implementation NSString (size)

- (CGSize)zz_sizeWithFont:(UIFont *)font maxW:(CGFloat)maxW
{
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSFontAttributeName] = font;
    CGSize maxSize = CGSizeMake(maxW, MAXFLOAT);
    return [self boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;
}
- (CGSize)zz_sizeWithFont:(UIFont *)font
{
    return [self zz_sizeWithFont:font maxW:MAXFLOAT];
}

-(CGFloat)zz_textHeight:(UIFont *)font{
    return [self sizeWithAttributes:@{NSFontAttributeName:font}].height;
}

- (CGRect)zz_fixWidthFrame:(CGFloat)width font:(UIFont *)font lineSpacing:(CGFloat)lineSpacing
{
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:lineSpacing];//调整行间距
    
    return [self boundingRectWithSize:CGSizeMake(width, 10000.0f) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName, paragraphStyle, NSParagraphStyleAttributeName, nil] context:nil];
}
@end


@implementation NSString (encipher)

- (NSString *)zz_base64Encoding {
    return [[self dataUsingEncoding:NSUTF8StringEncoding] base64EncodedStringWithOptions:0];
}

- (NSString *)zz_base64Decoding {
    return [[NSString alloc] initWithData:[[NSData alloc] initWithBase64EncodedString:self options:0] encoding:NSUTF8StringEncoding];
}

- (NSString *)zz_md5Encoding {
    const char *cStr = [self UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, (int)strlen(cStr), result); // This is the md5 call
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0],  result[1],  result[2],  result[3],
            result[4],  result[5],  result[6],  result[7],
            result[8],  result[9],  result[10], result[11],
            result[12], result[13], result[14], result[15]];
}

@end

@implementation NSString (Regex)

- (BOOL)zz_evaluateWithRegex:(NSString *)regex {
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    return [predicate evaluateWithObject:self];
}

- (NSString *)zz_substringWithRegex:(NSString *)regex {
    NSError *error = nil;
    NSRegularExpression *regularExpression = [NSRegularExpression regularExpressionWithPattern:regex options:NSRegularExpressionCaseInsensitive error:&error];
    if (!error) {
        NSTextCheckingResult *result = [regularExpression firstMatchInString:self options:NSMatchingReportProgress range:NSMakeRange(0, self.length)];
        return [self substringWithRange:result.range];
    }
    return @"";
}

- (NSArray <NSValue *> *)zz_rangesWithRegex:(NSString *)regex {
    NSError *error = nil;
    NSRegularExpression *regularExpression = [NSRegularExpression regularExpressionWithPattern:regex options:NSRegularExpressionCaseInsensitive error:&error];
    if (!error) {
        NSArray<NSTextCheckingResult *> *results = [regularExpression matchesInString:self options:NSMatchingReportProgress range:NSMakeRange(0, self.length)];
        NSMutableArray *ranges = [NSMutableArray arrayWithCapacity:[results count]];
        for (NSTextCheckingResult *result in results) {
            [ranges addObject:[NSValue valueWithRange:result.range]];
        }
        return [ranges copy];
    }
    return @[];
}

@end


